import json
import os

def save_items(state_or_manager, filepath=None):
    if filepath is None:
        filepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'data', 'items.json')
    try:
        os.makedirs(os.path.dirname(filepath), exist_ok=True)
        if isinstance(state_or_manager, dict):
            items = state_or_manager.get('items', [])
        else:
            items = getattr(state_or_manager, 'items', [])
        with open(filepath, 'w') as f:
            json.dump(items, f, ensure_ascii=False, indent=2)
        return True, "Items saved successfully."
    except Exception as e:
        return False, str(e)

def load_items(state_or_manager, filepath=None):
    if filepath is None:
        filepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'data', 'items.json')
    if not os.path.exists(filepath):
        return False, "File does not exist."
    try:
        with open(filepath, 'r') as f:
            items = json.load(f)
        if isinstance(state_or_manager, dict):
            from src.core import items as items_core
            items_core.load_items_into_state(state_or_manager, items)
        else:
            state_or_manager.clear()
            for item in items:
                state_or_manager.add_item(item['name'], item['price'], item['production_date'])
        return True, "Items loaded successfully."
    except Exception as e:
        return False, str(e)

if __name__ == "__main__":
    from src.core import items as items_core
    st = items_core.create_state()
    items_core.add_item(st, 'baguette', 2.50, '2024-01-15')
    print("Save:", save_items(st))
    items_core.delete_item(st, 1)
    print("Items after delete:", st['items'])
    print("Load:", load_items(st))
    print("Items after load:", st['items'])
